package com.profound.blog.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

public class MyBatisTemplate {

	public <C> int insert(String sqlID,C c){
		int count = -1;
		SqlSession s = null;
		try {
			s = SessionUtil.getSession();
			count = s.insert(sqlID,c);
			s.commit();
		} catch (Exception e) {
			// TODO: handle exception
			s.rollback();
			e.printStackTrace();
		}finally{
			s.close();
		}
		return count;
	}
	
	public <C> int update(String sqlID,C c){
		int count = -1;
		SqlSession s = null;
		try {
			s = SessionUtil.getSession();
			count = s.update(sqlID,c);
			s.commit();
		} catch (Exception e) {
			// TODO: handle exception
			s.rollback();
			e.printStackTrace();
		}finally{
			s.close();
		}
		return count;
	}
	
	public <T> T selectOne(String sqlID,Map map){
		T t = null;
		SqlSession s = null;
		try {
			s = SessionUtil.getSession();
			t = s.selectOne(sqlID, map);
			s.commit();
		} catch (Exception e) {
			// TODO: handle exception
			s.rollback();
			e.printStackTrace();
		}finally{
			if(null!=s){
			s.close();
			}
		}
		return t;
	}
	
	public <C> int delete(String sqlID,C c){
		int count = -1;
		SqlSession s = null;
		try {
			s = SessionUtil.getSession();
			count = s.delete(sqlID,c);
			s.commit();
		} catch (Exception e) {
			// TODO: handle exception
			s.rollback();
			e.printStackTrace();
		}finally{
			s.close();
		}
		return count;
	}
	
	public <T,C> T select(String sqlID,C c){
		T t = null;
		SqlSession s = null;
		try {
			s = SessionUtil.getSession();
			t = s.selectOne(sqlID, c);
			s.commit();
		} catch (Exception e) {
			// TODO: handle exception
			s.rollback();
			e.printStackTrace();
		}finally{
			s.close();
		}
		return t;
	}
	
	public <T,C> List<T> selectList(String sqlID,C c){
		List<T> list = null;
		SqlSession s = null;
		try {
			s = SessionUtil.getSession();
			list = s.selectList(sqlID, c);
			s.commit();
		} catch (Exception e) {
			// TODO: handle exception
			s.rollback();
			e.printStackTrace();
		}finally{
			s.close();
		}
		return list;
	}
}
